package com.itheima.travel.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.travel.pojo.ResultInfo;
import com.itheima.travel.pojo.User;
import com.itheima.travel.service.UserService;
import com.itheima.travel.utils.BeanFactory;
import com.itheima.travel.web.base.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * 在该类中处理用户模块相关的功能
 */
@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {
    private Logger logger = Logger.getLogger(UserServlet.class);

    /**
     * 退出登录
     * @param request
     * @param response
     */
    public void logout(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        request.getSession().invalidate();
        // 重定向到首页
        response.sendRedirect(request.getContextPath()+"/index.html");
    }

    /**
     * 查询用户登录状态
     * @param request
     * @param response
     *
     */
    public void getLoginStatus(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json;charset=utf-8");
        try {
            //1.获取session对象
            HttpSession session = request.getSession();
            //2.获取session中的用户信息
            User user = (User)session.getAttribute("user");
            //3.判断登录成功的状态
            ResultInfo resultInfo = new ResultInfo();
            if(user==null){
                // 没有用户登录
                resultInfo.setFlag(false);
            }else{
                // 有用户登录
                resultInfo.setFlag(true);
                resultInfo.setSuccessData(user);
            }
            String resultInfoJson = resultInfo.toJson(resultInfo);
            response.getWriter().print(resultInfoJson);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 用户登录
     * @param request
     * @param response
     */
    public void login(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json;charset=utf-8");
        try {
            ResultInfo resultInfo = new ResultInfo();
            //1.获取验证码
            String ucode = request.getParameter("ucode");
            System.out.println("请求携带的验证码: "+ucode);
            logger.info("请求携带的验证码: "+ucode);
            //2.获取session中生成的验证码
            HttpSession session = request.getSession();
            String scode = (String)session.getAttribute("scode");
            session.removeAttribute("scode");
            System.out.println("动态生成的验证码: "+scode);
            //3.判断验证码
            if(ucode==null||"".equals(ucode)){
                // 生成响应结果  "验证码不可为空"
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("验证码不可为空");
                String resultInfoJson = resultInfo.toJson(resultInfo);
                response.getWriter().print(resultInfoJson);
                return;
            }
            if(!ucode.equalsIgnoreCase(scode)){
                // 验证码错误
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("验证码不正确");
                String resultInfoJson = resultInfo.toJson(resultInfo);
                response.getWriter().print(resultInfoJson);
                return;
            }
            //4.获取用户名和密码,封装到user对象中
            Map<String, String[]> map = request.getParameterMap();
            User u = new User();
            BeanUtils.populate(u,map);
            System.out.println(u);
            logger.info("请求携带的用户信息为: "+u);
            //5.调用service处理业务逻辑
            // new对象的方式,让程序代码之间存在了耦合
            //UserService service = new UserService();
            // 使用工厂创建类对象
            UserService service = (UserService)BeanFactory.getBean("UserService");
            User user = service.login(u);
            //6.判断user对象,生成响应信息
            if (user==null){
                // 登录失败: 用户名或密码错误
                resultInfo.setFlag(false);
                resultInfo.setErrorMsg("用户名或密码错误");
            }else {
                // 登录成功
                resultInfo.setFlag(true);
                // 保存登录成功的状态
                session.setAttribute("user",user);
                // 重写JSESSIONID这个cookie
                Cookie cookie = new Cookie("JSESSIONID", session.getId());
                cookie.setMaxAge(30*60);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }
            String resultInfoJson = resultInfo.toJson(resultInfo);
            response.getWriter().print(resultInfoJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户注册
     * @param request
     * @param response
     */
    public void register(HttpServletRequest request, HttpServletResponse response) {
        try {
            //1.获取请求参数
            Map<String,String[]> map = request.getParameterMap();
            //2.封装到user对象中
            User user = new User();
            BeanUtils.populate(user,map);
            System.out.println(user);
            //3.调用service处理业务逻辑
            //UserService service = new UserService();
            // 使用工厂创建类对象
            UserService service = (UserService)BeanFactory.getBean("UserService");
            boolean flag = service.register(user);
            //4.判断执行结果,生成响应信息
            if(flag){
                response.getWriter().print(1);
            }else{
                response.getWriter().print(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /*protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.获取请求标识
        String action = request.getParameter("action");
        //2.判断请求标识
        if("register".equals(action)){
            register(request,response);
        }else if("login".equals(action)){
            login(request,response);
        }else if("getLoginStatus".equals(action)){
            getLoginStatus(request,response);
        }else if("logout".equals(action)){
            logout(request,response);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }*/
}